package com.itheima;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SpringApplicationContext {
    private String fileName;
    private Map<String, Object> beanMaps = new HashMap<String, Object>();

    public SpringApplicationContext(String fileName){
        this.fileName = fileName;
        parseXml();
    }

    private void parseXml() {
        try {
            SAXReader saxReader = new SAXReader();
            //2.根据文件名称获取文件的输入流
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(fileName);
            //3.读取文件获取Document对象
            Document document = saxReader.read(inputStream);
            //4.获取文档的根节点<beans>
            Element rootElement = document.getRootElement();
            //5.获取根节点下的所有<bean>节点
            List<Element> beanList = rootElement.elements();
            if (beanList!=null&& beanList.size()>0){
                for (Element element : beanList) {
                    //6.获取bean标签的id和class属性
                    String id = element.attributeValue("id");
                    String className = element.attributeValue("class");
                    //7.通过反射加载类对象
                    Class<?> name = Class.forName(className);
                    Object o = name.newInstance();
                    List<Element> proper = element.elements();
                    if (proper !=null&&proper.size()>0){
                        for (Element property : proper) {
                            String name1 = property.attributeValue("name");
                            Field field = name.getDeclaredField(name1);
                            field.setAccessible(true);
                            String value = property.attributeValue("value");
                            if (value !=null && !"".equals(value)){
                                field.set(o,value);
                            }
                        }
                    }
                    beanMaps.put(id,o);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public <T>T getBean(String beanId){
        return (T)beanMaps.get(beanId);
    }
}
